<!--  -->
<template>
  <div>
    <el-dialog
      title="添加线段"
      :visible.sync="xdDialogVisibal"
      width="1250px"
      append-to-body
      :close-on-click-modal="false"
      :destroy-on-close="true"
      top="2vh"
      v-dialogDrag
      @close="closeXDDialog"
      v-if="xdDialogVisibal"
    >
      <el-container style="border: 1px solid #f0f0f0;height: 600px; ">
        <el-aside width="210px" style="border: 1px solid #ffffff;overflow: auto;height: 100%;">    
          <div style="height: 100%;width: 100%;  overflow: auto;">
            <el-tree
              ref="leftTree"
              lazy
              :load="loadNode"
              :data="dwTree"
              node-key="label"
              :props="dwProps"
              :highlight-current="true"
              :default-expanded-keys="[this.label]"
              @node-click="handleDWNodeClick"
            ></el-tree>
          </div>
        </el-aside>
        <el-container style="border: 1px solid #f0f0f0">
          <el-main style="border: 1px solid #ffffff" width="280px">
            <el-row>
              <el-col :span="1"></el-col>
              <el-col :span="7">
                &nbsp;&nbsp;线段编码：
                <el-input v-model="xdQuery.xdbm" clearable size="mini" style="width: 120px" placeholder="线段编码"></el-input>
              </el-col>
              <el-col :span="7">  
                线段名称：
                <el-input v-model="xdQuery.xdmc" clearable size="mini" style="width: 120px" placeholder="线段名称"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button size="mini" class="search-btn" icon="el-icon-search" @click="handleXDSearch">查询</el-button>
              </el-col>
              <el-col :span="8" style="text-align: right;">
                <el-button size="mini" class="search-btn" icon="el-icon-delete" @click="closeXdAddDialog">关闭</el-button>
                <el-button size="mini" class="search-btn" type="primary" :autofocus="true" icon="el-icon-plus" @click="addXDInfo" :loading="addLoading">确定</el-button>
              </el-col>
            </el-row>
            <div style="border-bottom: 4px solid #ffffff"></div>

            <el-card class="box-card" shadow="never">
              <div slot="header">
                <span>线段数据</span>
                <el-button type="primary" size="mini" class="tz-table-btn" @click="xdAllCheck" :loading="xdCheckLoading">一键选中</el-button>
                <el-button type="primary" size="mini" class="tz-table-btn" @click="xdRemoveCheck">一键取消</el-button>
                <el-button type="primary" size="mini" class="tz-table-btn tz-table-pzl" icon="el-icon-setting" @click="cccEvent('show', zcxdTable, 'zcxd')">配置列</el-button>
              </div>
              <el-table
                :data="dialog_XDlist"
                ref="xdData"
                :header-cell-style="{'color':'#858585','font-weight':'400','background-color':'#fcfcfc'}"
                height="190"
                border
                size="mini"
                v-loading="dialog_XDlistLoading"
                :row-class-name="xdStyle"
                @row-click="xdRowClick"
                :header-cell-class-name="cellClass"
              >
                <el-table-column width="50" align="center" fixed="left">
                  <template slot-scope="scope">
                    <div @click.stop="xdCheckedClick(scope.row)">
                      <el-checkbox v-model="scope.row.checked" @change="xdCheckedChange(scope.row)"></el-checkbox>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="50" align="center" fixed="left"></el-table-column>
                <template v-for="col in zcxdcolumnData">
                  <el-table-column
                    :show-overflow-tooltip="true"
                    :key="col.id"
                    :prop="col.field"
                    :label="col.title"
                    :min-width="col.minWidth"
                    :align="col.align"
                    :header-align="col.align"
                    :sortable="col.sortable"
                    :formatter="col.formatter"
                    :fixed="col.fixed"
                  ></el-table-column>
                </template>
              </el-table>
              <div class="pagination-container">
                <el-pagination
                  @size-change="dialog_XDhandleSizeChange"
                  @current-change="dialog_XDhandleCurrentChange"
                  :current-page.sync="listQueryXd.current"
                  :page-size="listQueryXd.size"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="xdTotal"
                ></el-pagination>
              </div>
            </el-card>
            <!-- 占位符 -->
            <el-card class="box-card" shadow="never"></el-card>
            <el-card class="box-card" shadow="never">
              <div slot="header">
                <span>用户数据</span>
                <el-button type="primary" size="mini" class="tz-table-btn" @click="yhAllChcek">一键选中</el-button>
                <el-button type="primary" size="mini" class="tz-table-btn" @click="yhRemoveCheck">一键取消</el-button>
                <el-button size="mini" type="primary" class="tz-table-btn tz-table-pzl" icon="el-icon-setting" @click="cccEvent('show', zcyhTable,'zcyh')">配置列</el-button>
              </div>
              <el-table
                :data="dialog_YHlist"
                :header-cell-style="{'color':'#858585','font-weight':'400','background-color':'#fcfcfc'}"
                stripe
                height="190"
                border
                size="mini"
                v-loading="dialog_YHlistLoading"
                highlight-current-row
                :cell-style="yhCellStyle"
              >
                <el-table-column width="50" align="center" fixed="left">
                  <template slot="header" slot-scope="{ column, $index }">
                    <el-checkbox v-model="YHchecked" class="yhqx" style="display:none; "></el-checkbox>
                  </template>
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.checked" @change="YHcheckedChange(scope.row)"></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="50" align="center" fixed="left"></el-table-column>
                <template v-for="col in zcyhcolumnData">
                  <el-table-column
                    :show-overflow-tooltip="true"
                    :key="col.id"
                    :prop="col.field"
                    :label="col.title"
                    :min-width="col.minWidth"
                    :align="col.align"
                    :header-align="col.align"
                    :sortable="col.sortable"
                    :formatter="col.formatter"
                    :fixed="col.fixed"
                  ></el-table-column>
                </template>
              </el-table>
              <div class="pagination-container">
                <el-pagination
                  @size-change="dialog_YHhandleSizeChange"
                  @current-change="dialog_YHhandleCurrentChange"
                  :current-page.sync="listQueryYh.current"
                  :page-size="listQueryYh.size"
                  :page-sizes="[5, 10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="yhTotal"
                ></el-pagination>
              </div>                                                  
            </el-card>
          </el-main>
        </el-container>
      </el-container>
    </el-dialog>
    <ccc ref="ccc"></ccc>
  </div>
</template>

<script>
import { getZczyTree, getZczyTable, getZczyYhTable, getZczyYhTableAll } from "@/api/sjwh/zczy.js";
import { addYxzyXdTemp } from "@/api/sjwh/yxzyxd.js";
import ccc from "@/dialogCommom/ccc";
export default {
  data() {
    return {
      addLoading: false,
      xdCheckLoading: false,
      TOKEN: 0,
      flagZs: "0", //添加线段失败，回传
      xdid_list: [], //存在
      xdDialogVisibal: false,
      dwbm: "",
      xdQuery: {
        //线段---查询条件
        xdbm: "",
        xdmc: "",
      },
      list_xd: [], //选择的线段（已选择线段-》停电范围）
      dwTree: [], //单位树数据
      dwProps: {
        //单位树 默认展开字段
        children: "children",
        label: "label",
        isLeaf: "leaf",
      },
      listQuerryTree: {
        //单位树 查询条件
        dwbm: "string",
        level: 0,
        showChild: "1",
        showXlmc: "1",
        xdbmLike: "string",
      },
      label: "", //懒加载 默认展开标识
      node_had: [],
      resolve_had: [],
      dialog_XDlist: [], //所有线段数据
      xdCheckRow: {}, //当前选中线段
      dialog_XDlistLoading: false, //线段loading
      listQueryXd: {
        //线段查询条件
        current: 1,
        size: 10,
        dwbm: [],
        sjqssj: "",
        sjzzsj: "",
        xdbm: "", //点击查询
        xdmc: "", //点击查询
        xlbm: "", //点击左边tree -> xdbm
        sjId: "",
        // neIds: [], //过滤已选线段的数据
        ascs: ["xdbm"], //排序
        tyzt: "0"
      },

      xdTotal: 0, //线段总长度
      dialog_XDSelection: [], // 线段数据勾选的多条数据
      dialog_XDSelection_bf: [], // 线段数据勾选数据的备份
      dialog_XDSelection_bf_qx: {}, // 线段数据取消勾选第一行的数据
      dialog_XDSelection_row: [], // 线段数据当前勾选的一条行数据

      dialog_flag: false, // 节流阀
      dialog_YHlistLoading: false, //用户loading
      dialog_YHlist: [], //用户数据
      dialog_YHlistAll: [], //当前线段下的所有用户数据(已过滤双电源、空载变等)
      dialog_YHlistBigAll: [], //全选线段时候查询出来的用户
      listQueryYh: {
        //用户查询条件
        current: 1,
        size: 10,
        dwbm: [], //单位编码
        sjqssj: "",
        sjzzsj: "",
        xdId: "", //线段ID
        sjId: "",
        ascs: ["yhbm"], //排序
        tyzt: "1"
      }, 
      listQueryYhAll: {
        //所有用户查询条件
        dwbm: [], //单位编码
        sjqssj: this.xdPardata.qssj,
        sjzzsj: this.xdPardata.zzsj,
        xdId: "", //线段ID
        sjId: "",
        tyzt: "1"
      },
      yhTotal: 0, //用户总长度
      YHchecked: false, // 用户数据全选按钮

      zcxdcolumnData: [], //线段的 列
      zcyhcolumnData: [], //用户的 列
      zcxdTable: "zc_zyxdsj", //线段 配置列请求参数
      zcyhTable: "zc_zyyhsj", //用户 配置列请求参数
    };
  },

  props: {
    /**父级组件传过来的值 */
    xdPardata: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },

  components: {
    ccc,
  },

  computed: {},

  watch: {
    /**监听父节点传过来的值 */
    xdPardata(newVal, oldVal) {
      
      if (newVal) {
        this.TOKEN = newVal.TOKEN,
        this.xdDialogVisibal = newVal.visibal;
        this.dwbm = newVal.dwbm;
          
        this.listQueryXd.sjId = newVal.sjId;
        this.listQueryYh.sjId = newVal.sjId;
        this.listQueryYhAll.sjId = newVal.sjId;

        if (newVal.list_xd_show.length > 0) {
          //有选择的线段
          this.list_xd_show = newVal.list_xd_show;
        } else {
          //未选择线段
          this.list_xd_show = [];
        }
      }
    },
  },

  created() {
    this.zcxdEvent("load", this.zcxdTable);
    this.zcyhEvent("load", this.zcyhTable);
  },

  mounted() {},

  beforeUpdate() {
    //解决列配置引发的滚动条问题
  },

  update() {},

  destroyed() {},

  methods: {
    yhCellStyle({ row, column, rowIndex, columnIndex }) {
      //当数据类型为待维护，或者为待审核的时候
      if (row.issdy == "1") {
        return "color: red;";
      } else {
        if (row.gylxm == "1" || row.gylxm == "2" || row.gylxm == "3") {
          return "color: #E6A23C;"
        }
      }
    },
    /**取消线段 */
    closeXdAddDialog() {
     
      this.xdDialogVisibal = false;
      this.dialog_XDlist = [];
      this.dialog_YHlist = [];
      this.xdid_list = [];
      this.clearDatas();
      localStorage.clear();
      this.addLoading = false;
      this.xdCheckLoading = false;
      if(this.flagZs == "1"){
        this.$emit("handleAddYxxd", true);
      }
    },
    /**关闭线段 */
    closeXDDialog() {
      this.xdDialogVisibal = false;
      this.dialog_XDlist = [];
      this.dialog_YHlist = [];
      this.xdid_list = [];
      this.clearDatas();
      localStorage.clear();
      if(this.flagZs == "1"){
        this.$emit("handleAddYxxd", true);
      }
    },
    /**添加线段---》停电范围列表数据 */
    addXDInfo() {
    
      if (this.xdid_list.length == 0) {
        this.$message.info("请至少勾选一个线段！");
        return;
      }
      let yhid_list = [];
      this.xdid_list.forEach((item) => {
        delete item.checked
        JSON.parse(localStorage.getItem(item.id)).forEach((item1) => {
          delete item1.checked
          yhid_list.push(item1);
        });
      });
      let reqData = {
        TOKEN: this.TOKEN,
        sjId: this.xdPardata.sjId,
        zcxdList: this.xdid_list,
        zcyhList: yhid_list,
        czy: this.xdPardata.czy
      };
      this.addLoading = true;
      addYxzyXdTemp(reqData).then((res) => {
 
        if (res.code === 0 && res.data) {
          //清空缓存
          this.xdid_list.forEach((item) => {
            localStorage.removeItem(item.id);
          });
          //关闭弹窗
          this.xdDialogVisibal = false; 
          //回传成功添加的data
          this.$emit("handleAddYxxd", res.data);
          //添加完成，清除一些数据
          this.dialog_XDlist = [];
          this.dialog_YHlist = [];
          this.xdid_list = [];
          this.clearDatas();
          this.addLoading = false;
        }else{
          this.flagZs = "1"; //修改线段失败，发生操作，运行线段查询临时表
          this.$message.error(res.message);
          this.addLoading = false;
        }
      });
      

      // let xdArray = this.xdid_list.map((item) => {
      //   return {
      //     yxxd: item,
      //     yxyh: JSON.parse(localStorage.getItem(item.id)),
      //   };
      // });

      // xdArray.forEach((item) => {
      //   if (item.yxyh.length === 0) {
      //     this.$message.warning(
      //       "当前已选择线段中包含空用户，请检查，重新选择！"
      //     );
      //     return false;
      //   }
      // });
    },
    /**添加完成，获取取消弹窗，做清除弹窗操作 */
    clearDatas(){
      this.listQueryXd.current = 1;
      this.listQueryXd.size = 10;
      this.xdTotal = 0;
      this.listQueryYh.current = 1;
      this.listQueryYh.size = 10;
      this.yhTotal = 0;
    },
    /**当前线段高亮标识 */
    xdStyle({ row, rowIndex }) {
      let arr = this.dialog_XDSelection_row;
      for (let i = 0; i < arr.length; i++) {
        if (row == arr[i]) {
          return "rowStyle";
        }
      }
    },
    // 隐藏线段头部
    cellClass(row) {
      if (row.columnIndex === 0) {
        return "DisableSelection";
      }
    },
    // 线段数据 单机行方法
    xdRowClick(row, column, event) {
      this.YHchecked = false;
      this.dialog_XDSelection_row = [row];
      this.listQueryYh.dwbm = [row.dwbm];
      this.listQueryYh.xdId = row.id;
      this.getYHList();
    },

    /**阻止线段点击向上冒泡 */
    xdCheckedClick(val) {},
    /**选择线段 */
    xdCheckedChange(row) {
     
      this.dialog_XDSelection_row = [row];
      //根据n的值，n !=null 则不是线段自己勾选，n === null，就是没查到，那么就是线段自己勾选
      //根据nList的值，判断线段是否存在本地了
      let n = localStorage.getItem(row.id);

      if (row.checked === true) {
       
        //xdid_list不存在勾选线段
        this.xdid_list.push(row);

        this.xdCheckRow = row;
        //查询当前页用户
        this.listQueryYh.dwbm = [row.dwbm];
        this.listQueryYh.xdId = row.id;
        //查询所有用户
        this.listQueryYhAll.dwbm = [row.dwbm];
        this.listQueryYhAll.xdId = row.id;
        this.getYHListAll(); //查询当前xdId对应的 所有用户（已过滤双电源、空载变等）
        // this.getYHList(); //查询当前xdid对应的 当前页用户
      } else {
        //删除当前勾选新单
        this.xdid_list.splice(
          this.xdid_list.findIndex((item) => item.id === row.id),
          1
        ); //删除当前勾选线段

        localStorage.removeItem(row.id);
        this.listQueryYh.dwbm = [row.dwbm];
        this.listQueryYh.xdId = row.id;
        this.getYHList();
      }
    },
    /**线段 一键选中（当前页） */
    xdAllCheck() {
      //过滤出当前页未勾选的线段
      let noCheckXd = this.dialog_XDlist.filter(
        (item) => item.checked === false
      );
      //定义临时数组，存储未勾选线段 (row)，需要存到xdid_list 里面去的
      let xdIds = [];
      noCheckXd.forEach((item) => {
        xdIds.push(item);
      });

      //存储 纯xdid 的数组，存储{id:'',yhList: []}的数组
      let xdid_list_time = noCheckXd.map((item, index) => {
        return {
          id: item.id,
          yhList: [],
        };
      });
      if (xdIds.length === 0) {
        //当前页线段无可选线段
        this.$message.warning(
          "当前页面无可选中线段！"
        );
        return;
      }
      //定义存储 纯xdid的数组，用于请求所有用户数据使用
      let xdIdsYh = noCheckXd.map((item) => {
        return item.id;
      });
      let listQuery = {
        dwbm: [noCheckXd[0].dwbm],
        sjqssj: this.xdPardata.qssj,
        sjzzsj: this.xdPardata.zzsj,
        xdId: xdIdsYh,
      };
      this.xdCheckLoading = true;
      getZczyYhTableAll(listQuery).then((response) => {
        
        let dialog_YHlistBigAll = response.data;
        xdid_list_time.forEach((item) => {
          //处理线段，过滤双电源、空载变用户
          dialog_YHlistBigAll.forEach((item1) => {
            if (item.id === item1.xdId && item1.issdy != "1") {
              item.yhList.push(item1);
            }
          });
        });

        let filter_xdid_list = xdid_list_time.filter((item) => {
          if (item.yhList.length > 0) {
            return item;
          }
        });

        if (filter_xdid_list.length > 0) {
          //当前有可以选择的线段
          //1. 当前页线段列表选中
          this.dialog_XDlist.forEach((item) => {
            filter_xdid_list.forEach((item1) => {
              if (item.id === item1.id) {
                this.$set(item, "checked", true);
              }
            });
          });

          filter_xdid_list.forEach((item) => {
            //2. 本地存储
            localStorage.setItem(item.id, JSON.stringify(item.yhList));
          });
          let filte_row_xdid_ist = this.dialog_XDlist.forEach((item) => {
            filter_xdid_list.forEach((item1) => {
              if (item.id === item1.id) {
                //3. 存储id，push到xdid_list
                this.xdid_list.push(item);
              }
            });
          });
        } else {
          //当前页没有可以选择的线段
          this.$message.warning(
            "当前列表中可一键勾选线段已全部勾选，请勿重复操作！"
          );
          this.xdCheckLoading = false;
          return;
        }

        if (
          this.listQueryYh.xdId !== "" &&
          this.dialog_XDSelection_row.length > 0
        ) {
          this.getYHList();
        }
        this.xdCheckLoading = false;
      });

      //判断dialog_XDSelection_row的值，决定是否查询用户

      // this.getYHList();
    },
    /**线段 一键取消（当前页） */
    xdRemoveCheck() {
      //1. 取当前页与缓存 交集   2.取消选中状态   3.清除对应缓存、清除xdid_list对应线段
      let intersection = this.dialog_XDlist.filter((item) => {
        //求交集
        let idList = this.xdid_list.map((v) => v.id);
        return idList.includes(item.id);
      });

      let difference = this.xdid_list.filter((item) => {
        //求差集
        let idList = intersection.map((v) => v.id);
        return !idList.includes(item.id);
      });

      //如果当前页有选中的xdid存在 intersection.length > 0   1.取消当前页选中  2.清除xdid_list对应的xdid  3.清除缓存
      if (intersection.length > 0) {
        this.dialog_XDlist.forEach((item) => {
          intersection.forEach((item1) => {
            if (item.id === item1.id) {
              this.$set(item, "checked", false);
            }
          });
        });
        this.xdid_list = difference;
        intersection.forEach((item) => {
          localStorage.removeItem(item.id);
        });
        if (
          this.listQueryYh.xdId !== "" &&
          this.dialog_XDSelection_row.length > 0
        ) {
          this.getYHList();
        }
      } else {
        this.$message.warning("当前页不存在选中线段，请不要重复操作！");
      }
    },

    /**用户一键全选 */
    yhAllChcek() {
   
      //判断当前选中线段是否存在本地
      let n = localStorage.getItem(this.listQueryYh.xdId);
    
      if (n != null) {
        //存在本地

        //获取本地存储
        let ret = JSON.parse(n);
        //筛选出 本地存储 与 当前页数据 的交集
        let intersection = this.dialog_YHlist.filter((item) => {
          let idList = ret.map((v) => v.id);
          return idList.includes(item.id);
        });

        //取当前页线段与存储的线段 有差集部分
        let difference = this.dialog_YHlist.filter((item) => {
          let idList = intersection.map((v) => v.id);
          return !idList.includes(item.id);
        });

        //过滤差集中的 “双电源用户”
        let noSdyyhList = difference.filter((item) => item.issdy !== "1");

        this.dialog_YHlist.forEach((item) => {
          //选中差集用户
          noSdyyhList.forEach((item1) => {
            if (item.id === item1.id) {
              this.$set(item, "checked", true);
            }
          });
        });

        let newLocStorage = [...ret, ...noSdyyhList];
     
        localStorage.setItem(
          this.listQueryYh.xdId,
          JSON.stringify(newLocStorage)
        );
      } else {
        //不存在本地
        let dialogYhlist = JSON.parse(JSON.stringify(this.dialog_YHlist))
        //判断当前用户数据是否为空
        if(dialogYhlist.length <= 0){
          this.$message.warning("当前页无可选中用户！")
          return
        }
 
        let screenYhList = this.dialog_YHlist.filter((item) => {
          if (item.issdy != "1") {
            return item;
          }
        });

        if(screenYhList.length <= 0){
          this.$message.warning("当前页只有双电源用户，不可选中！")
          return
        }
        this.dialog_YHlist.forEach((item) => {
          //选中用户
          screenYhList.forEach((item1) => {
            if (item.id === item1.id) {
              this.$set(item, "checked", true);
            }
          });
        });
        this.dialog_XDlist.forEach((item) => {
          //选中线段
          if (item.id === this.listQueryYh.xdId) {
            this.$set(item, "checked", true);
          }
        });
        let xdInterSection = this.dialog_XDlist.filter(
          (item) => item.id === this.listQueryYh.xdId
        );
        this.xdid_list.push(xdInterSection[0]);
        localStorage.setItem(
          this.listQueryYh.xdId,
          JSON.stringify(screenYhList)
        ); //存本地
      }
    },
    /**用户一键清除 */
    yhRemoveCheck() {
 
      let n = localStorage.getItem(this.listQueryYh.xdId);
      //根据当前页的选中数据，判断是否需要做 “一键清空” 的操作

      if (n != null) {
       
        let ret = JSON.parse(n);
     
        //拿到当前页用户 与 本都存储用户的交集（array）
        let intersection = this.dialog_YHlist.filter((item) => {
          let idList = ret.map((v) => v.id);
          return idList.includes(item.id);
        });
   
        this.dialog_YHlist.forEach((item) => {
          intersection.forEach((item1) => {
            if (item.id === item1.id) {
              this.$set(item, "checked", false);
            }
          });
        });
        //本地存储与交集 之间的差集
        let callRet = ret.filter((item) => {
          let idList = intersection.map((v) => v.id);
          return !idList.includes(item.id);
        });
      
        if (callRet.length > 0) {
          //当前线段还有已选择用户存在
          localStorage.setItem(this.listQueryYh.xdId, JSON.stringify(callRet));
        } else {
          //当前线段 没有已选择的用户
          localStorage.removeItem(this.listQueryYh.xdId);
          this.dialog_XDlist.forEach((item) => {
            if (item.id === this.listQueryYh.xdId) {
              this.$set(item, "checked", false);
            }
          });
          this.xdid_list.splice(
            this.xdid_list.findIndex(
              (item) => item.id === this.listQueryYh.xdId
            ),
            1
          ); //删除当前勾选线段
        }
      } else {
        
        this.$message.warning("当前页无可选用户，请不要重复操作！")
      }
    },

    /**用户单击选择（双电源、空载变等都可以选择） */
    YHcheckedChange(val) {
      let n = localStorage.getItem(this.listQueryYh.xdId);
      if (val.checked === true) {
       
        if (n != null) {
          //本地存在
          let ret = [...JSON.parse(n), ...[val]];
          localStorage.setItem(this.listQueryYh.xdId, JSON.stringify(ret));
        } else {
          //本地不存在
          localStorage.setItem(this.listQueryYh.xdId, JSON.stringify([val]));
          // this.xdid_list.push(this.listQueryYh.xdId);
          let xdInterSection = this.dialog_XDlist.filter(
            (item) => item.id === this.listQueryYh.xdId
          );
          this.xdid_list.push(xdInterSection[0]);

          this.dialog_XDlist.forEach((item) => {
            if (item.id === this.listQueryYh.xdId) {
              this.$set(item, "checked", true);
            }
          });
        }
      } else {
       
        //本地一定存在
        let ret = JSON.parse(n);
        ret.splice(
          ret.findIndex((item) => item.id === val.id),
          1
        );
        if (ret.length > 0) {
          //还有用户存在
          localStorage.setItem(this.listQueryYh.xdId, JSON.stringify(ret));
        } else {
          //没有用户存在了
          this.dialog_XDlist.forEach((item) => {
            if (item.id === this.listQueryYh.xdId) {
              this.$set(item, "checked", false);
            }
          });
          localStorage.removeItem(this.listQueryYh.xdId);
          //删除当前勾选线段
          this.xdid_list.splice(
            this.xdid_list.findIndex(
              (item) => item.id === this.listQueryYh.xdId
            ),
            1
          ); 
    
        }
      }
    },

    /**点击线段查询 */
    handleXDSearch() {
      // 判断查线段还是查用户
      // 如果线段，看是否选择了本页的单位，有则用本页选中的单位做条件
      var xdbm = this.xdQuery.xdbm;
      var xdmc = this.xdQuery.xdmc;
      if (xdbm == "" && xdmc == "") {
        this.$message.warning("线段编码或名称不能为空！");
        return;
      }
      let xlbm = this.listQueryXd.xlbm;
 
      if(xlbm == "" || xlbm == null){
        this.$message.warning("请先选择线路节点！");
        return;
      }
      //if(node.jb==6){
      this.listQueryXd.xdbm = xdbm;
      this.listQueryXd.xdmc = xdmc; //搜索-线段编码
      this.getXDList();
      //}
    },
    /**获取线段数据 */
    getXDList() {
  
      this.dialog_YHlist = []; //清除用户数据
      this.dialog_XDSelection_row = [];

      this.dialog_XDlistLoading = true;
      this.listQueryXd.sjqssj = this.xdPardata.qssj;
      this.listQueryXd.sjzzsj = this.xdPardata.zzsj;


      getZczyTable(this.listQueryXd).then((response) => {
        //拿到返回值
        let reqXdList = JSON.parse(JSON.stringify(response.data.records));
        //创建新的数组
        let newXdlist = [];
        //判断父级线段是否传值过来
        if (this.list_xd.length > 0) {
          //差集
          newXdlist = reqXdList.filter((item) => {
            let idList = this.list_xd.map((v) => v);
            return !idList.includes(item.id);
          });
        } else {
          newXdlist = reqXdList;
        }
        //给 当前台账线段表格赋值
        this.dialog_XDlist = newXdlist;

        //判断本地存储xdid列表，如果存在，则对应的线段需要打上勾，如果没有，则本页线段数据checked属性为false
        // let nList = localStorage.getItem("xdid_list");
        if (this.xdid_list.length > 0) {
          //存在
          // 取当前页线段与存储的线段 有交集部分
          let intersection = this.dialog_XDlist.filter((item) => this.xdid_list.some((v) => v.id == item.id));

          let difference = this.dialog_XDlist.filter((item) => {
            let idList = intersection.map((v) => v.id);
            return !idList.includes(item.id);
          });

          if (intersection.length > 0) {
            //有交集
            this.dialog_XDlist.forEach((item) => {
              intersection.forEach((item1) => {
                if (item === item1) {
                  this.$set(item, "checked", true);
                }
              });
            });
            this.dialog_XDlist.forEach((item) => {
              difference.forEach((item1) => {
                if (item === item1) {
                  this.$set(item, "checked", false);
                }
              });
            });
          } else {
            //没有交集
            this.dialog_XDlist.forEach((item) => {
              this.$set(item, "checked", false);
            });
          }
        } else {
          //不存在
          this.dialog_XDlist.forEach((item) => {
            if (item.checked == undefined) {
              this.$set(item, "checked", false);
            }
          });
        }

        this.xdTotal = response.data.total;
        this.dialog_XDlistLoading = false;
      });
    },
    /**线段分页 */
    dialog_XDhandleSizeChange(val) {
      this.listQueryXd.size = val;
      this.listQueryXd.current = 1;
      this.getXDList();
    },
    /**线段分页 */
    dialog_XDhandleCurrentChange(val) {
      this.listQueryXd.current = val;
      this.getXDList();
    },

    /**获取用户数据 */
    getYHList() {
      this.dialog_YHlistLoading = true;
      this.listQueryYh.sjqssj = this.xdPardata.qssj;
      this.listQueryYh.sjzzsj = this.xdPardata.zzsj;
      let listQueryYh = JSON.parse(JSON.stringify(this.listQueryYh))
      listQueryYh.xdId = [this.listQueryYh.xdId]
      getZczyYhTable(listQueryYh).then((response) => {
        this.dialog_YHlist = response.data.records;
        this.yhTotal = response.data.total;
        let localYhAllList = JSON.parse(
          localStorage.getItem(this.listQueryYh.xdId)
        );
        if (localYhAllList != null) {
          //本地存在 此xdid用户

          //先取交集
          let intersection = this.dialog_YHlist.filter((item) => {
            let idList = localYhAllList.map((v) => v.id);
            return idList.includes(item.id);
          });
          //再取差集
          let difference = this.dialog_YHlist.filter((item) => {
            let idList = intersection.map((v) => v.id);
            return !idList.includes(item.id);
          });
          this.dialog_YHlist.forEach((item) => {
            intersection.forEach((item1) => {
              if (item.id === item1.id) {
                this.$set(item, "checked", true);
              }
            });
          });

          this.dialog_YHlist.forEach((item) => {
            difference.forEach((item1) => {
              if (item.id === item1.id) {
                this.$set(item, "checked", false);
              }
            });
          });
        } else {
          //本地不存 此xdid用户
          this.dialog_YHlist.forEach((item) => {
            this.$set(item, "checked", false);
          });
        }

        this.dialog_YHlistLoading = false;
      });
    },

    /**获取当前选择线段的所有用户数据 */
    async getYHListAll() {
      let listQueryYhAll = JSON.parse(JSON.stringify(this.listQueryYhAll))
      listQueryYhAll.xdId = [this.listQueryYhAll.xdId]
      getZczyYhTable(listQueryYhAll).then((response) => {
        let reqData = response.data.records;
        let newFilData = [];
        reqData.forEach((item) => {
          if (item.issdy == "0") {
            //过滤双电源用户
            newFilData.push(item);
          }
        });
        this.dialog_YHlistAll = newFilData;
        if (this.dialog_YHlistAll.length > 0) {
          localStorage.setItem(
            this.listQueryYh.xdId,
            JSON.stringify(this.dialog_YHlistAll)
          );
          this.getYHList();
     
        } else {
          this.dialog_XDlist.forEach((item) => {
            if (item.id === this.listQueryYhAll.xdId) {
              this.$set(item, "checked", false);
            }
          });
          // this.xdid_list.splice(this.listQueryYhAll.xdId, 1); //删除当前勾选新单
          this.xdid_list.splice(
            this.xdid_list.findIndex(
              (item) => item === this.listQueryYhAll.xdId
            ),
            1
          ); //删除当前勾选线段
      
          this.$message({
            message: `线段 “${this.xdCheckRow.xdbm}” 下无可选择用户，该线段不可选中`,
            type: "warning",
          });
        }
      });
    },

    dialog_YHhandleSizeChange(val) {
      this.listQueryYh.size = val;
      this.listQueryYh.current = 1;
      this.getYHList();
    },
    dialog_YHhandleCurrentChange(val) {
      this.listQueryYh.current = val;
      this.getYHList();
    },

    /**点击树 */
    handleDWNodeClick(data) {
      if (data.data.level == 2) {
        if (this.xdid_list.length > 0) {
          this.$message.warning("切换线，已选择的线段、用户将会被清空！");
          this.xdid_list.length = [];
          localStorage.clear();
        }
        this.listQueryXd.xdbm = "";
        this.listQueryXd.xdmc = "";
        this.listQueryXd.dwbm = [data.data.dwbm];
        this.listQueryXd.xlbm = data.data.xdbm;
        this.listQueryXd.current = 1;
        this.listQueryXd.size = 10;

        this.getXDList();
      }
    },
    // 线段树 懒加载方法
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.node_had = node; //这里是关键！在data里面定义一个变量，将node.level == 0的node存起来
        this.resolve_had = resolve; //同上，把node.level == 0的resolve也存起来
        this.requestTree(resolve);
      } else if (node.level >= 1) {
        this.getIndex(node, resolve);
      } else if (node.level > 2) {
        return resolve([]);
      }
    },
    // 一级树
    requestTree(resolve) {
      let reqData = {
        dwbm: this.dwbm,
        showAll: '',
        level: ""
      };
      getZczyTree(reqData).then((res) => {
        if (res.code === 0) {
          let req = res.data;
          this.label = req[0].label;
          this.dwTree = req;
          return resolve(req);
        } else {
          return resolve([]);
        }
      });
    },
    /** 二级树 */
    getIndex(node, resolve) {
      let reqData = {
        dwbm: this.dwbm,
        level: node.data.data.level,
        xdbmLike: node.data.data.xdbm,
        showAll: ''
      };

      if (this.list_xd_show !== undefined && this.list_xd_show.length > 0) {
        let xdbm = this.list_xd_show[0].xdbm;
        reqData.xdbmLike = xdbm.substring(0, 5);
      }

      getZczyTree(reqData).then((res) => {
        if (res.code === 0) {
          let req = res.data;
          for (let i = 0; i < req.length; i++) {
            if (req[i].data.level >= 2) {
              req[i].name = "leaf";
              req[i].leaf = true;
            }
          }
          return resolve(req);
        } else {
          return resolve([]);
        }
      });
    },

    /**配置列 */
    cccEvent(method, table, type) {
      if (method === "show") {
        if (type == "zcxd") {
          this.$refs.ccc.show(this.zcxdTable, type);
        } else if (type == "zcyh") {
          this.$refs.ccc.show(this.zcyhTable, type);
        }
      } else if (method === "load") {
        new Promise((resolve, reject) => {
          resolve(this.$refs.ccc.load(table));
        }).then((response) => {
          if (type == "zcxd") {
            this.zcxdcolumnData = response;
          } else if (type == "zcyh") {
            this.zcyhcolumnData = response;
          }
        });
      } else if (method === "export") {
        let vo = {
          tableCode: table,
          param: this.listQuery,
          url: "",
          method: "GET",
          fileName: "",
        };
        this.$refs.ccc.exportExcel(vo);
      }
    },
    /**初次加载 中压用户列 */
    zcxdEvent(method, table) {
      if (method === "show") {
        this.$refs.ccc.show(table);
      } else if (method === "load") {
        new Promise((resolve, reject) => {
          this.$nextTick(() => {
            resolve(this.$refs.ccc.load(table));
          });
        }).then((response) => {
          this.zcxdcolumnData = response;
        });
      } else if (method === "export") {
        let vo = {
          tableCode: table,
          param: this.listQuery,
          url: "",
          method: "GET",
          fileName: "",
        };
        this.$refs.ccc.exportExcel(vo);
      }
    },

    /**初次加载 中压线段列 */
    zcyhEvent(method, table) {
      if (method === "show") {
        this.$nextTick(() => {
          this.$refs.ccc.show(table);
        });
      } else if (method === "load") {
        new Promise((resolve, reject) => {
          this.$nextTick(() => {
            resolve(this.$refs.ccc.load(table));
          });
        }).then((response) => {
          this.zcyhcolumnData = response;
        });
      } else if (method === "export") {
        let vo = {
          tableCode: table,
          param: this.listQuery,
          url: "",
          method: "GET",
          fileName: "",
        };
        this.$refs.ccc.exportExcel(vo);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
  /deep/ .el-table--striped .el-table__body tr.el-table__row--striped.current-row td{
    background-color: #a2ccfb;
  }
  /deep/ .el-table tbody tr:hover > td {
    background-color: #a2ccfb !important;
  }
  /deep/  .el-table__row.hover-row td {
    background-color: #a2ccfb;
  }
  /deep/ .el-table__body tr.current-row>td{
    background-color: #a2ccfb;
  }
  /deep/ .el-table__body tr.hover-row>td {
    background-color: #a2ccfb;
  }
  
/deep/ .el-tree-node__content{
  &:hover{
    background-color: #a2ccfb;
  }
}
/deep/ .el-tree-node.is-current > .el-tree-node__content {
    background-color: #a2ccfb !important;
  }
</style>
<style lang='scss' scoped>

/deep/ .el-dialog__header {
  padding: 4px 10px 4px;
}
/deep/ .el-dialog__headerbtn {
  top: 10px;
}
.el-dialog__body {
  padding: 3px 10px;
}
.el-main {
  padding: 2px;
}
.el-card__body {
  padding: 3px;
}
.tz-table-btn {
  padding: 5px 10px;
}
/deep/.el-card .el-card__header {
  padding: 4px 10px;
}
/deep/.el-card .el-card__body {
  padding: 3px;
}
/deep/ .el-tree > .el-tree-node {
  min-width: 100%;
  display: inline-block;
}
.pagination-container {
  text-align: center;
}
.tz-table-pzl {
  float: right;
}
</style>
